import CommentModel from '@/model/Comment'
import PostModel from '@/model/Post'
import { checkCode, getJWTPayload } from '@/common/utils'
import UserModel from '@/model/User'
import CommentHands from '@/model/CommentHands'

const canReply = async (ctx) => {
  const obj = await getJWTPayload(ctx.header.authorization)
  let result = false
  if (obj) {
    const user = await UserModel.findOne({ _id: obj._id })
    if (user) {
      if (user.status === 1) {
        result = true
      }
    }
  }

  return result
}
class CommentController {
  async getCommentsList (ctx) {
    const { tid = '', page = 0, limit = 10 } = ctx.query
    if (!tid) {
      ctx.body = {
        code: 403,
        msg: '文章id不能为空'
      }
      return
    }
    let result = await CommentModel.getCommentList(tid, page, parseInt(limit))
    const total = await CommentModel.countDocuments({ tid })
    const obj = await getJWTPayload(ctx.header.authorization)
    if (obj) {
      result = result.map((item) => item.toJSON())
      for (let i = 0; i < result.length; i++) {
        const item = result[i]
        item.handed = 0
        const hands = await CommentHands.findOne({ cid: item._id, uid: obj._id })
        if (hands) {
          item.handed = 1
        }
      }
    }
    ctx.body = {
      code: 200,
      data: result,
      total,
      msg: 'success'
    }
  }

  // 获取用户评论
  async getUserComments (ctx) {
    const { uid, page = 0, limit = 10 } = ctx.query
    const res = await CommentModel.getUserCommentList(uid, page, limit)
    ctx.body = {
      code: 200,
      data: res
    }
  }

  // 添加评论
  async addComment (ctx) {
    const canCheck = await canReply(ctx)
    if (!canCheck) {
      ctx.body = {
        code: 403,
        msg: '用户已被禁言'
      }
      return
    }
    const { body } = ctx.request
    const { sid, code, tid } = body
    const check = await checkCode(sid, code)
    if (!check) {
      ctx.body = {
        code: 403,
        msg: '验证码错误'
      }
      return
    }
    const obj = await getJWTPayload(ctx.header.authorization)
    const post = await PostModel.findOne({ _id: tid })
    if (!post || post.status === 1) {
      ctx.body = {
        code: 403,
        msg: '文章不存在或该文章关闭回复'
      }
      return
    }
    const comment = new CommentModel(body)
    comment.cuid = obj._id
    comment.tuid = post.uid
    comment.save()
    await PostModel.updateOne({ _id: tid }, { $inc: { answer: 1 } })
    const total = await CommentModel.getUserMsgCount(post.uid)
    global.ws.send(post.uid, { event: 'message', message: total })
    ctx.body = {
      code: 200,
      data: comment,
      msg: '评论成功'
    }
  }

  // 更新评论
  async updateComment (ctx) {
    const canCheck = await canReply(ctx)
    if (!canCheck) {
      ctx.body = {
        code: 403,
        msg: '用户已被禁言'
      }
      return
    }
    const { body: { cid, id, sid, code, content } } = ctx.request
    const obj = await getJWTPayload(ctx.header.authorization)
    if (obj._id !== cid) {
      ctx.body = {
        code: 403,
        msg: '不能编辑别人的帖子'
      }
      return
    }
    const check = await checkCode(sid, code)
    if (!check) {
      ctx.body = {
        code: 403,
        msg: '验证码不正确'
      }
      return
    }
    const result = await CommentModel.updateOne({
      _id: id
    }, {
      $set: { content }
    })
    ctx.body = {
      code: 200,
      data: result,
      msg: '更新评论成功'
    }
  }

  // 设置最佳
  async setBestComment (ctx) {
    const { body: { tid, id } } = ctx.request
    const post = await PostModel.findOne({ _id: tid })
    if (!post) {
      ctx.body = {
        code: 404,
        msg: '文章不存在'
      }
      return
    }
    if (post.isEnd === 1) {
      ctx.body = {
        code: 404,
        msg: '文章已结贴，无法设置最佳'
      }
      return
    }
    await PostModel.updateOne({ _id: tid }, {
      $set: { isEnd: 1 }
    })
    const comment = await CommentModel.findOne({ _id: id })
    if (!comment) {
      ctx.body = {
        code: 404,
        msg: '评论不存在，无法设置'
      }
      return
    }
    await CommentModel.updateOne({ _id: id }, {
      $set: { isBest: 1 }
    })
    const result = await UserModel.updateOne({
      _id: comment.cuid
    }, {
      $inc: { favs: post.favs }
    })
    ctx.body = {
      code: 200,
      msg: '设置成功',
      data: result
    }
  }

  // 点赞
  async setHands (ctx) {
    const { body: { id } } = ctx.request
    const obj = await getJWTPayload(ctx.header.authorization)
    const handsRecord = await CommentHands.findOne({ cid: id, uid: obj._id })
    if (handsRecord) {
      ctx.body = {
        code: 403,
        msg: '您已经点过赞了，请勿重复点击'
      }
      return
    }
    const result = await CommentModel.updateOne({ _id: id }, {
      $inc: { hands: 1 }
    })
    if (result.ok === 1) {
      const hands = new CommentHands({
        cid: id,
        uid: obj._id
      })
      await hands.save()
      ctx.body = {
        code: 200,
        data: hands,
        msg: '点赞成功'
      }
    } else {
      ctx.body = {
        code: 500,
        msg: '更新失败'
      }
    }
  }

  // 获取用户未读消息
  async getUserMsg (ctx) {
    const { page = 0, limit = 10 } = ctx.query
    const obj = await getJWTPayload(ctx.header.authorization)
    const res = await CommentModel.getUserMsgList(obj._id, page, parseInt(limit))
    const total = await CommentModel.getUserMsgCount(obj._id)
    ctx.body = {
      code: 200,
      data: res,
      total
    }
  }

  // 已读消息
  async readUserMsg (ctx) {
    const { cid } = ctx.request.body
    const obj = await getJWTPayload(ctx.header.authorization)
    // 指定某条消息
    if (cid) {
      await CommentModel.updateOne({ _id: cid, tuid: obj._id }, { $set: { isRead: 1 } })
    } else {
      // 清除所有
      await CommentModel.updateMany({ tuid: obj._id }, { $set: { isRead: 1 } })
    }
    ctx.body = {
      code: 200,
      msg: '删除成功'
    }
  }
}

export default new CommentController()
